/***************************************************************************
[FileName]
-------------------
    begin                : [FileDate]
    copyright            : by kuzkok
    email                : kuzkok@gmail.com

***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*   
*   Данная программа является свободным программным обеспечением;         *
*   Вы можете распространять ее и/или модифицировать в соответствии с     *
*   GNU General Public License опубликованной Фондом свободного           *
*   программного обеспечения; используемая версия лицензии - 2 или        *
*   (по вашему выбору) любая более поздняя                                *
***************************************************************************/

/*! объекты уникальные в рамках плагина */
#include <QMessageBox>
#include <QDialog>
#include <QTextEdit>

#include "qgsmapcanvas.h"
#include "qgsmaplayer.h"
#include "qgsdatasourceuri.h"
#include "qgsvectorlayer.h"


#include "unique.h"
#include "dbconnection.h"

unique* unique::myInst=0;

unique* unique::inst()
{
    if(!myInst)
    {
        myInst = new unique();
    }
    return myInst;
}

QgsMapLayer *unique::findLayer(QString theLayerName)
{
    if(mQgisIface)
    {
        QgsMapCanvas *canvas = mQgisIface->mapCanvas();
        dbconnection *db = dbconnection::instance();
        for(int i=0;i<canvas->layerCount();i++)
        {
            QgsMapLayer *layer=canvas->layer(i);
            if(layer->type()==0 && layer->source().contains("dbname"))
            {
                QgsDataSourceURI dsURI(layer->source());
                if(dsURI.host()==db->database().hostName() &&
                   dsURI.database()==db->database().databaseName() &&
                   dsURI.table()==theLayerName.remove('"')
                   ){
                    return layer;
                }
            }
        }
    }
    return 0;
}

QString unique::extentToWKT(QgsRectangle theExtent)
{
    QString result =
            QString("%1 %2, %1 %4, %3 %4, %3 %2, %1 %2")
            .arg(theExtent.xMinimum(), 0, 'g', 16)
            .arg(theExtent.yMinimum(), 0, 'g', 16)
            .arg(theExtent.xMaximum(), 0, 'g', 16)
            .arg(theExtent.yMaximum(), 0, 'g', 16);
    return result;
}

void unique::calcMByExtent(QgsRectangle *theExtent)
{    
    QgsVectorLayer *vl = static_cast<QgsVectorLayer*>(findLayer("stationseries"));
    //QgsFeatureList *selfeatures = vl->selectedFeatures();
    if(vl)
    {
        QgsRectangle Extent = mQgisIface->mapCanvas()->extent();
        //QMessageBox::information(0, "info", Extent.toString());
        QgsRectangle layerExtent = mQgisIface->mapCanvas()->mapRenderer()->mapToLayerCoordinates(vl, Extent);
        //QMessageBox::information(0, "info", extentToWKT(layerExtent));

        QSqlQuery query(dbconnection::instance()->database());
        query.prepare(
                "select max(st_m(geom)) mmax, min(st_m(geom)) mmin "
                "from"
                "   (select (st_dumppoints(st_force_4d(geom))).geom as geom from stationseries) as inter "
                "where "
                " st_intersects(inter.geom, "
                "               st_geomfromewkt('SRID=4326;POLYGON(("+extentToWKT(layerExtent)+"))'))"
                );
        if(query.exec())
        {
            QSqlRecord rec = query.record();
            query.next();
            QMessageBox::information(0,
                                     "m coordinates",
                                     QString("mmin: %1; mmax: %2")
                                     .arg(query.value(rec.indexOf("mmin")).toString())
                                     .arg(query.value(rec.indexOf("mmax")).toString())
                                     );
        }
        else
            QMessageBox::information(0, "error", query.lastError().text());
//        vl->select( QgsAttributeList(), layerExtent, true, true );
//        QgsFeature f;
//        QString ster;
//        while( vl->nextFeature( f ))
//        {
//            ster += QString("%1; ").arg(f.id());
//        }
//        QMessageBox::information(0, "info", ster);

    }
    else
        QMessageBox::information(0, "info", "layer null");
    //vl->extent()
    //vl->select(theExtent, false);
    //vl->nextFeature(


}

unique::~unique()
{}

unique::unique()
{}

QgsMapCanvas *unique::mapCanvas()
{
    return inst()->mQgisIface->mapCanvas();
}
